package com.fish.anne.service.impl;

import java.util.List;

import org.springframework.security.providers.encoding.PasswordEncoder;

import com.fish.anne.dao.SystemAdminRoleDao;
import com.fish.anne.dao.SystemAdminUserDao;
import com.fish.anne.model.SystemAdminRole;
import com.fish.anne.model.SystemAdminUser;
import com.fish.anne.service.SystemAdminUserManager;

public class SystemAdminUserManagerImpl extends GenericManagerImpl<SystemAdminUser, Long> implements SystemAdminUserManager {
	SystemAdminUserDao systemAdminUserDao;

	public SystemAdminUserManagerImpl(SystemAdminUserDao systemAdminUserDao) {
		super(systemAdminUserDao);
		this.systemAdminUserDao = systemAdminUserDao;
	}

	public void remove(Long adminId) {
		// TODO Auto-generated method stub
		systemAdminUserDao.remove(adminId);
		systemAdminRoleDao.removeByAdminId(adminId);
	}

	private PasswordEncoder passwordEncoder;
	SystemAdminRoleDao systemAdminRoleDao;

	public void setSystemAdminRoleDao(SystemAdminRoleDao systemAdminRoleDao) {
		this.systemAdminRoleDao = systemAdminRoleDao;
	}

	public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
		this.passwordEncoder = passwordEncoder;
	}

	public SystemAdminUser getByNameAndPassword(String name, String password) {
		password = passwordEncoder.encodePassword(password, null);
		return systemAdminUserDao.getByNameAndPassword(name, password);
	}

	public void updateSystemAdminUserPassword(SystemAdminUser systemAdminUser) {

		String password = passwordEncoder.encodePassword(systemAdminUser.getUserpass(), null);
		systemAdminUser.setUserpass(password);

		this.systemAdminUserDao.updateSystemAdminUserPassword(systemAdminUser);
	}

	public SystemAdminUser save(SystemAdminUser adminUser) {
		List<SystemAdminRole> systemAdminRoles = adminUser.getSystemAdminRoles();
		if (adminUser.isChangepwd()) {
			String password = passwordEncoder.encodePassword(adminUser.getUserpass(), null);
			adminUser.setUserpass(password);
		}

		adminUser = systemAdminUserDao.save(adminUser);
		if (systemAdminRoles != null) {
			for (SystemAdminRole sar : systemAdminRoles) {
				if (sar == null)
					continue;
				if (sar.getArId() == null & sar.getRoleId() != null) {
					sar.setAdminId(adminUser.getAdminId());
					systemAdminRoleDao.save(sar);
				} else if (sar.getArId() != null & sar.getRoleId() == null) {
					systemAdminRoleDao.remove(sar.getArId());
				}
			}
		}

		return adminUser;
	}
}